import requests
from DBUtils.PooledDB import PooledDB
import threading
import time
import pymysql

# 查找字符串中某字符第N次出现的位置下标
def findSubStrIndex(substr, str, time):
    times = str.count(substr)
    if (times == 0) or (times < time):
        pass
    else:
        i = 0
        index = -1
        while i < time:
            index = str.find(substr, index+1)
            i+=1
        return index

ID = "ww7b4086d88a144eec"
SECRET = "Yy-hdts7KZHFDO8tzwWTNUfPiGyssUOo8XAPz2IOnbA"
url_get_access_token = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + ID + "&corpsecret=" + SECRET

#获取access_token#
'''
def get_access_token(ID,SECRET):
    access_token_json = requests.get(url_get_access_token).json()
    while access_token_json['errcode'] != 0:
        get_access_token(ID, SECRET)
        time.sleep(2)
    access_token = access_token_json['access_token']
    return access_token
'''

access_token_json = requests.get(url_get_access_token).json()
access_token = access_token_json['access_token']

#获取通讯录成员列表#
url_get_member_list = "https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?access_token=" + access_token + "&department_id=1&fetch_child=1"

def pool():
    pool = PooledDB(pymysql, 20, host='127.0.0.1', user='root', passwd='zcxvbmn', db='weixindb', port=3306)
    return pool

def clean_member_list():
    db = pool().connection()
    cursor = db.cursor()
    clean_member_list_sql = "delete from member_list"
    cursor.execute(clean_member_list_sql)
    db.commit()
    db.close()
    return

member_list = requests.get(url_get_member_list).json()['userlist']
print(len(member_list))

def get_member_detail(member):
    db = pool().connection()
    cursor = db.cursor()
    member["userid"] = repr(member["userid"])
    member["department"] = member["department"][0] #随机取一个部门
    member["name"] = repr(member["name"])
    #所在获取部门名称
    get_department_name_sql = "select name from department_list where id=%d" % (member["department"])
    cursor.execute(get_department_name_sql)
    department_name = cursor.fetchone()[0]
    department_id = member["department"]
    while department_id != 1:
        get_parentid_sql = "select parentid from department_list where id=%d" % (department_id)
        cursor.execute(get_parentid_sql)
        parentid = cursor.fetchone()[0]
        get_parent_department_name_sql = "select name from department_list where id=%d" % (parentid)
        cursor.execute(get_parent_department_name_sql)
        parent_department_name = cursor.fetchone()[0]
        department_name = parent_department_name + "/" + department_name
        department_id = parentid
    member["department_name"] = repr(department_name)
    cols = ", ".join('{}'.format(k) for k in member.keys())
    val_cols = ', '.join('{}'.format(k) for k in member.values())
    insert_member_list_sql = "insert into member_list(%s) values(%s)" % (cols, val_cols)
    try:
        cursor.execute(insert_member_list_sql)
        db.commit()
    except:
        print(insert_member_list_sql)
    db.close()
    '''
        # 获取员工岗位
        url_get_member_detail = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=" + get_access_token(ID, SECRET) + "&userid=" + eval(member["userid"])
        member_detail = requests.get(url_get_member_detail).json()
        member["position"] = repr(member_detail.setdefault("position", 0))
        url_get_client_list = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/list?access_token=" + get_access_token(ID, SECRET) + "&userid=" + eval(member["userid"])
        client_list = requests.get(url_get_client_list).json()['external_userid']
        member["client_count"] = len(client_list)  # 获取员工顾客总数#
        #下面注释掉的是获取企微顾客数#
        for client in client_list:
            i = 1  # i为计数器
            next_cursor = ''
            while i == 1 or next_cursor != '':
            url_get_client_detail = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/get?access_token=" + get_access_token(ID, SECRET) + "&external_userid=" + client
    '''
    return

def get_member_detail_task(start_num, end_num):
    for member in member_list[start_num:end_num]:
        get_member_detail(member)
        time.sleep(0.005)
    return

def get_member_list_threading_task():
    for n in range(0, len(member_list), 1000):
        start_num = n
        end_num = n + 999
        task_threading = threading.Thread(target=get_member_detail_task, args=(start_num, end_num))
        task_threading.start()
    return

clean_member_list()
get_member_list_threading_task()